

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Created by zhangyilin on 2018/11/15.
 */

/****
 *
 * 教师查看自己创建的班级
 */
public class ClassBelong extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setContentType("text/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        response.setCharacterEncoding("UTF-8");//setContentType与setCharacterEncoding的顺序不能调换，否则还是无法解决中文乱码的问
        String ClassBlonger =(String) request.getSession().getAttribute("ID");
        try {
            //写数据库访问
            Class.forName("com.mysql.jdbc.Driver");
            Connection connect = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/ListSystem", "root", "");
            Statement stmt = connect.createStatement(); //创建Statement对象
            String sql;
            sql = "SELECT *FROM Class_t WHERE ClassBlonger='"+ClassBlonger+"'";
            ResultSet rs = stmt.executeQuery(sql);
//            rs.last();
//            int n = rs.getRow();
//            System.out.println(n);
            if(rs.next()){
                out.print("{\"classArr\":[");
                rs.first();
                String myString1 =  "{\"class_name\":\"" + rs.getString(2) + "\",\"class_key\":\"" + rs.getString(1)+ "\"}";
                out.print(myString1);

                while (rs.next()){
//                n--;
                    String myString = "{\"class_name\":\"" + rs.getString(2) + "\",\"class_key\":\"" + rs.getString(1)+ "\"}";
//                System.out.println(","+myString);
                    out.print(","+myString);

                }
                out.print("]}");
            }
            else {
                out.print("{\"classArr\":[");
                out.print("]}");
            }

            out.close();
            stmt.close();
            connect.close();
        }catch (Exception e) {
            out.print("get data error!");
            e.printStackTrace();
        }
    }

}
